package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.R;
import com.sun.prism.impl.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "loginFilter", urlPatterns = "/*")
@Slf4j
public class LoginFilter implements Filter {
    private static AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String[] urls = {"/employee/login",
                "/backend/**",
                "/front/**",
                "/user/**"
        };
        for (String url : urls) {
            boolean match = antPathMatcher.match(url, request.getRequestURI());
            if (match) {
                filterChain.doFilter(request, response);
                return;
            }
        }
        HttpSession session = request.getSession();
        Long employee = (Long) session.getAttribute("employee");
        Long userId = (Long) session.getAttribute("userId");
        if (employee != null) {
            filterChain.doFilter(request, response);
            return;
        }
        if (userId != null) {
            filterChain.doFilter(request, response);
            return;
        }
        String jsonString = JSON.toJSONString(R.error("NOTLOGIN"));
        response.getWriter().write(jsonString);
        return;
    }
}
